﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace SharpShare.Afp.Protocol {
    public struct AfpToken {
        private byte[] _value;

        public AfpToken(byte[] value) {
            if (value == null) {
                value = new byte[0];
            }

            _value = new byte[value.Length];

            Array.Copy(value, _value, value.Length);
        }

        public static bool operator ==(AfpToken token1, AfpToken token2) {
            return (token1.Equals(token2));
        }
        public static bool operator !=(AfpToken token1, AfpToken token2) {
            return !(token1.Equals(token2));
        }

        public bool IsEmpty {
            get {
                return (_value == null || _value.Length == 0);
            }
        }

        public byte[] ToByteArray() {
            if (_value == null) {
                return new byte[0];
            }

            byte[] value = new byte[_value.Length];
            Array.Copy(_value, value, _value.Length);
            return value;
        }

        public override bool Equals(object obj) {
            if (!(obj is AfpToken)) {
                return false;
            }

            AfpToken other = (AfpToken)obj;

            if (this._value.Length != other._value.Length) {
                return false;
            }

            for (int x = 0; x < _value.Length; x++) {
                if (_value[x] != other._value[x]) {
                    return false;
                }
            }

            return true;
        }

        public override int GetHashCode() {
            int code = 0;

            for (int x = 0; x < _value.Length; x++) {
                code ^= _value[x];
            }

            return code;
        }

        public override string ToString() {
            return BitConverter.ToString(_value);
        }

        public static AfpToken Generate(int length) {
            RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
            byte[] token = new byte[length];
            random.GetBytes(token);
            return new AfpToken(token);
        }
    }
}
